package com.tbynet.jwp.web;

import com.jfinal.aop.Inject;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Path;
import com.tbynet.jwp.framework.core.JwpController;
import com.tbynet.jwp.service.TermService;
import com.tbynet.jwp.service.dto.request.TermRequest;
import com.tbynet.jwp.service.dto.response.TermResponse;

import java.math.BigInteger;
import java.util.Arrays;

/**
 * 后台分类项管理控制器
 * 负责接收后台管理相关的HTTP请求，调用Manager层处理业务，返回响应
 * 只负责路由转发，不包含任何业务逻辑
 *
 * @author 佰亿互联
 * @version 1.0
 * @since 2025-11-04
 */
@Path(value = "/web/admin/term", viewPath = "/web/")
public class TermAdminController extends JwpController {

    // 分类项管理器
    @Inject
    TermService termService;

    /**
     * 页面渲染
     * 对应路由：GET /web/admin/term 或 GET /web/admin/term/edit
     */
    public void index()  {
        render(getPara(0, "index") + ".html");
    }

    /**
     * 创建分类项
     * 对应路由：POST /admin/api/term/create
     */
    @ActionKey("/admin/api/term/create")
    public void create() {
        // 获取请求参数并构建请求对象
        TermRequest request = new TermRequest();
        request.setName(getPara("name"));
        request.setSlug(getPara("slug"));
        request.setTaxonomy(getPara("taxonomy"));
        request.setParentId(getParaToBigInteger("parentId"));
        request.setDescription(getPara("description"));
        request.setUserId(getParaToBigInteger("userId"));

        // 调用Manager层创建分类项
        TermResponse.DetailInfo result = termService.createTerm(request);

        // 返回响应
        if (result != null) {
            renderJson(buildSuccess("创建分类项成功", result));
        } else {
            renderJson(buildBusinessError("CREATE_TERM_FAILED", "创建分类项失败"));
        }
    }

    /**
     * 更新分类项
     * 对应路由：PUT /admin/api/term/update
     */
    @ActionKey("/admin/api/term/update")
    public void update() {
        // 获取请求参数并构建请求对象
        TermRequest request = new TermRequest();
        request.setTermId(getParaToBigInteger("id"));
        request.setName(getPara("name"));
        request.setSlug(getPara("slug"));
        request.setTaxonomy(getPara("taxonomy"));
        request.setParentId(getParaToBigInteger("parentId"));
        request.setDescription(getPara("description"));
        request.setUserId(getParaToBigInteger("userId"));

        // 调用Manager层更新分类项
        TermResponse.DetailInfo result = termService.updateTerm(request);

        // 返回响应
        if (result != null) {
            renderJson(buildSuccess("更新分类项成功", result));
        } else {
            renderJson(buildBusinessError("UPDATE_TERM_FAILED", "更新分类项失败"));
        }
    }

    /**
     * 删除分类项
     * 对应路由：DELETE /admin/api/term/delete
     */
    @ActionKey("/admin/api/term/delete")
    public void delete() {
        // 获取参数
        BigInteger termId = getParaToBigInteger("id");
        String taxonomy = getPara("taxonomy");

        // 调用Manager层删除分类项
        Boolean success = termService.deleteTerm(termId, taxonomy);

        // 返回响应
        if (success) {
            renderJson(buildSuccess("删除分类项成功", null));
        } else {
            renderJson(buildBusinessError("DELETE_TERM_FAILED", "删除分类项失败"));
        }
    }

    /**
     * 批量删除分类项
     * 对应路由：POST /admin/api/term/batch_delete
     */
    @ActionKey("/admin/api/term/batch_delete")
    public void batchDelete() {
        // 获取参数并构建请求对象
        TermRequest request = new TermRequest();
        request.setTermIds(Arrays.asList(getParaValuesToBigInteger("termIds[]")));
        request.setTaxonomy(getPara("taxonomy"));

        // 调用Manager层批量删除分类项
        TermResponse.BatchOperationResult result = termService.batchDeleteTerms(request);

        // 返回响应
        if (result != null && result.getSuccessCount() > 0) {
            renderJson(buildSuccess("批量删除分类项完成", result));
        } else {
            renderJson(buildBusinessError("BATCH_DELETE_TERM_FAILED", "批量删除分类项失败"));
        }
    }

    /**
     * 获取分类项详情
     * 对应路由：GET /admin/api/term/get
     */
    @ActionKey("/admin/api/term/get")
    public void get() {
        // 获取参数
        BigInteger termId = getParaToBigInteger("id");
        String taxonomy = getPara("taxonomy");

        // 调用Manager层获取分类项详情
        TermResponse.DetailInfo result = termService.getTermDetail(termId, taxonomy);

        // 返回响应
        if (result != null) {
            renderJson(buildSuccess("获取分类项详情成功", result));
        } else {
            renderJson(buildBusinessError("TERM_NOT_FOUND", "分类项不存在"));
        }
    }

    /**
     * 分页查询分类项列表
     * 对应路由：GET /admin/api/term/list
     */
    @ActionKey("/admin/api/term/list")
    public void list() {
        // 构建查询请求
        TermRequest request = new TermRequest();
        request.setTaxonomies(Arrays.asList(getParaValues("taxonomies")));
        request.setPageNumber(getParaToInt("page", 1));
        request.setPageSize(getParaToInt("size", 20));
        request.setOrderBy(getPara("orderBy"));
        request.setOrder(getPara("order"));
        request.setSearch(getPara("search"));
        request.setHideEmpty(getParaToBoolean("hideEmpty", false));

        // 调用Manager层获取分类项列表
        TermResponse.ListResult result = termService.listTerms(request);

        // 返回响应
        renderJson(buildSuccess("获取分类项列表成功", result));
    }

    /**
     * 获取分类项层级结构
     * 对应路由：GET /admin/api/term/hierarchy
     */
    @ActionKey("/admin/api/term/hierarchy")
    public void hierarchy() {
        // 获取参数
        String taxonomy = getPara("taxonomy");
        BigInteger parentId = getParaToBigInteger("parentId");

        // 调用Manager层获取层级结构
        TermResponse.HierarchyResult result = termService.getTermHierarchy(taxonomy, parentId);

        // 返回响应
        renderJson(buildSuccess("获取分类项层级结构成功", result));
    }

    /**
     * 获取分类项统计信息
     * 对应路由：GET /admin/api/term/statistics
     */
    @ActionKey("/admin/api/term/statistics")
    public void statistics() {
        // 调用Manager层获取统计信息
        TermResponse.Statistics result = termService.getTermStatistics();

        // 返回响应
        renderJson(buildSuccess("获取分类项统计信息成功", result));
    }

    /**
     * 设置分类项元数据
     * 对应路由：POST /admin/api/term/meta/set
     */
    @ActionKey("/admin/api/term/meta/set")
    public void setMeta() {
        // 获取参数
        BigInteger termId = getParaToBigInteger("id");
        String metaKey = getPara("metaKey");
        Object metaValue = getPara("metaValue");

        // 调用Manager层设置元数据
        Boolean success = termService.setTermMeta(termId, metaKey, metaValue);

        // 返回响应
        if (success) {
            renderJson(buildSuccess("设置分类项元数据成功", null));
        } else {
            renderJson(buildBusinessError("SET_TERM_META_FAILED", "设置分类项元数据失败"));
        }
    }

    /**
     * 获取分类项元数据
     * 对应路由：GET /admin/api/term/meta/get
     */
    @ActionKey("/admin/api/term/meta/get")
    public void getMeta() {
        // 获取参数
        BigInteger termId = getParaToBigInteger("id");
        String metaKey = getPara("metaKey");

        // 调用Manager层获取元数据
        Object result = termService.getTermMeta(termId, metaKey);

        // 返回响应
        renderJson(buildSuccess("获取分类项元数据成功", result));
    }

    /**
     * 更新分类项计数
     * 对应路由：POST /admin/api/term/update_count
     */
    @ActionKey("/admin/api/term/update_count")
    public void updateCount() {
        // 获取参数
        BigInteger termId = getParaToBigInteger("id");
        String taxonomy = getPara("taxonomy");

        // 调用Manager层更新计数
        Boolean success = termService.updateTermCount(termId, taxonomy);

        // 返回响应
        if (success) {
            renderJson(buildSuccess("更新分类项计数成功", null));
        } else {
            renderJson(buildBusinessError("UPDATE_TERM_COUNT_FAILED", "更新分类项计数失败"));
        }
    }

    /**
     * 清理空分类项
     * 对应路由：POST /admin/api/term/cleanup
     */
    @ActionKey("/admin/api/term/cleanup")
    public void cleanup() {
        // 获取参数
        String taxonomy = getPara("taxonomy");

        // 调用Manager层清理空分类项
        TermResponse.BatchOperationResult result = termService.cleanupUnusedTerms(taxonomy);

        // 返回响应
        if (result != null) {
            renderJson(buildSuccess("清理空分类项完成", result));
        } else {
            renderJson(buildBusinessError("CLEANUP_TERMS_FAILED", "清理空分类项失败"));
        }
    }

    /**
     * 搜索分类项
     * 对应路由：GET /admin/api/term/search
     */
    @ActionKey("/admin/api/term/search")
    public void search() {
        // 获取参数
        String keyword = getPara("keyword");
        String taxonomy = getPara("taxonomy");
        Integer limit = getParaToInt("limit", 20);

        // 调用Manager层搜索分类项
        TermResponse.ListResult result = termService.searchTerms(keyword, taxonomy, limit);

        // 返回响应
        renderJson(buildSuccess("搜索分类项成功", result));
    }
}